package com.lcj.nebula.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import toolgood.words.IllegalWordsSearch;
import toolgood.words.IllegalWordsSearchResult;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class SensitiveWordUtil {

    static List<String> keyWordList = new ArrayList<>();

    public SensitiveWordUtil() throws Exception {
        try {
            Resource resource = new ClassPathResource("sensitive/KeyWords.txt");
            InputStream is = resource.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            keyWordList = reader.lines().collect(Collectors.toList());
        } catch (IOException e) {
            throw new Exception("SensitiveWordUtil初始化失败,src/resource/sensitive/KeyWords.txt不存在");
        }
    }

    public List<String> findSensitive(String str) {
        //创建检测器
        IllegalWordsSearch illegalWordsSearch = new IllegalWordsSearch();
        illegalWordsSearch.SetKeywords(keyWordList);
        List<IllegalWordsSearchResult> illegalWordsSearchResults = illegalWordsSearch.FindAll(str);

        List<String> res = new ArrayList<>();
        for (IllegalWordsSearchResult illegalWordsSearchResult : illegalWordsSearchResults) {
            if(!res.contains(illegalWordsSearchResult.Keyword)) {
                res.add(illegalWordsSearchResult.Keyword);
            }
        }
        log.info("toolgood敏感词检测结果：{}", res);
        return res;
    }

    /**
     * 判断是否包含非法词
     * @param chatMessages
     * @return isSensitive
     */
    public static Boolean isSensitive(String chatMessages) {
        //创建检测器
        IllegalWordsSearch illegalWordsSearch = new IllegalWordsSearch();
        //设置关键词
        illegalWordsSearch.SetKeywords(keyWordList);
        boolean res = illegalWordsSearch.ContainsAny(chatMessages);
        return res;
    }

    /**
     * 替换非法词为***
     * @param str
     * @return Health String
     */
    public static String replace(String str) {
        //创建检测器
        IllegalWordsSearch illegalWordsSearch = new IllegalWordsSearch();
        illegalWordsSearch.SetKeywords(keyWordList);
        //替换敏感词
        String res = illegalWordsSearch.Replace(str);
        return res;
    }
}
